const express = require('express');
const app = express();
const session = require('express-session');
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true
}))
// 托管静态页面
app.use(express.static('./pages'));
app.use(express.json())
// 解析 POST 提交过来的表单数据
app.use(express.urlencoded({extended: false}))

// 登录的 API 接口
app.post('/api/login', (req, res) => {
    console.log(req.body)
    // 判断用户提交的登录信息是否正确
    if (req.body.username !== 'admin' || req.body.password !== '000000') {
        return res.send({status: 1, msg: '登录失败'})
    }
    req.session.user = req.body
    req.session.islogin = true
    res.send({status: 0, msg: '登录成功'})
})

app.get('/api/username', (req, res) => {
    // 从 Session 中获取用户的名称，响应给客户端
    if (!req.session.islogin) {
        return res.send({status: 1, msg: 'fail'})
    }
    res.send({status: 0, msg: 'success', username: req.session.user.username})
})

app.post('/api/logout', (req, res) => {
    // 清空 Session 信息
    req.session.destroy()
    res.send({status: 0, msg: '退出登录成功'})
})

app.listen(8888, () => console.log('Express server running at http://127.0.0.1:8888'))